package com.example.parallelandroid;

import static android.content.Context.MODE_PRIVATE;
import static cn.bmob.v3.Bmob.getApplicationContext;
import static cn.bmob.v3.Bmob.initialize;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Shader;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.example.parallelandroid.utils.SPUtils;
import com.example.parallelandroid.utils.StepDateUtils;
import com.example.parallelandroid.utils.StepUtil;
import com.google.android.material.imageview.ShapeableImageView;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.internal.Util;

public class RoleFragment extends Fragment {
    //提醒的dialog
    private MyDialog myDialog;
    private RequestOptions requestOptions = RequestOptions.circleCropTransform()
            .diskCacheStrategy(DiskCacheStrategy.NONE)//不做磁盘缓存
            .skipMemoryCache(true);//不做内存缓存
    private SharedPreferences user,sp;
    private boolean autoLogin;
    private String userId;
    private SharedPreferences.Editor editor;

    private int back_flag=1;
    // 与侧滑菜单有关的控件
    private ShapeableImageView ivBtn;
    private DrawerLayout drawerLayout;
    private ShapeableImageView ivAvatar;
    private TextView bioTextView,tvNickname,todayStudyTime,todaySteps,powerTextView,charmTextView,intelligenceTextView,comprehensiveTextView,textWearSuitTextView,textWearWeaponSuitTextView;
    private ListView listView;
    View view=null;
    private MySettingAdapter arrayAdapter;
    private List<String> strings = new ArrayList<>();
    private ImageView roleImageView,roleWeaponImageView;
    //刷新布局控件
    private SmartRefreshLayout smartRefreshLayout;
    //用于保留三位小数的工具
    java.text.DecimalFormat dff=new java.text.DecimalFormat("0.00");
    java.text.DecimalFormat dfff=new java.text.DecimalFormat("0.000");
    //Handler里用于刷新页面的常量
    private final int REFRESH = 1;
    //用于刷新页面的Handler
    private Handler myHandler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //处理子线程发送的消息
            switch (msg.what){
                case REFRESH:
                    //更新页面
                    updatePage();
                    //结束刷新的动画
                    smartRefreshLayout.finishRefresh();
                    break;
            }
        }
    };
    //处理下拉刷新和上拉加载更多事件的方法
    private void setListener(){
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                    //下拉刷新时回调，需要请求最新的数据
                    initSp();
            }
        });
    }
    @SuppressLint("MissingInflatedId")
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // 获取布局文件
        view = inflater.inflate(R.layout.fragment_role, null);
        //绑定控件
        init();
        //后端获取数据
        initSp();
        //更新页面
        updatePage();
        //字体渐变色加载
        textColorSet();
        //更新步数
        todaySteps.setText("今日运动步数:"+ (int)StepUtil.getTodayStep(this.getContext()));
        // 设置监听
        setListener();
        ivBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawerLayout.openDrawer(Gravity.LEFT);
            }
        });
        // 返回布局文件对象
        return view;
    }

    private void textColorSet() {
        //红色渐变色
        LinearGradient mLinearGradient = new LinearGradient(0, 0, 0, todaySteps.getPaint().getTextSize(), Color.RED, Color.BLACK, Shader.TileMode.CLAMP);
        LinearGradient redLinearGradient = new LinearGradient(0, 0, 0, todaySteps.getPaint().getTextSize(), Color.BLACK, Color.RED, Shader.TileMode.CLAMP);
        //绿色渐变色
        LinearGradient linearGradient=new LinearGradient(0, 0, 0, powerTextView.getPaint().getTextSize(), Color.GREEN, Color.BLACK, Shader.TileMode.CLAMP);
        //蓝色
        LinearGradient blue_linearGradient=new LinearGradient(0, 0, 0, powerTextView.getPaint().getTextSize(), Color.BLUE, Color.BLACK, Shader.TileMode.CLAMP);
        LinearGradient blackLinearGradient=new LinearGradient(0, 0, 0, bioTextView.getPaint().getTextSize(), Color.BLACK, Color.BLACK, Shader.TileMode.CLAMP);
        todaySteps.getPaint().setShader(redLinearGradient);
        todayStudyTime.getPaint().setShader(mLinearGradient);
        powerTextView.getPaint().setShader(blue_linearGradient);
        intelligenceTextView.getPaint().setShader(linearGradient);
        comprehensiveTextView.getPaint().setShader(blue_linearGradient);
        charmTextView.getPaint().setShader(linearGradient);
        bioTextView.getPaint().setShader(blackLinearGradient);
        //得到字体库类型
        Typeface typeface = Typeface.createFromAsset(getContext().getAssets(),
                "包图小白体.ttf");
        Typeface handwriting = Typeface.createFromAsset(getContext().getAssets(),
                "演示秋鸿楷.ttf");
        tvNickname.setTypeface(typeface);
        todayStudyTime.setTypeface(typeface);
        todaySteps.setTypeface(typeface);
        powerTextView.setTypeface(typeface);
        intelligenceTextView.setTypeface(typeface);
        comprehensiveTextView.setTypeface(typeface);
        charmTextView.getPaint().setTypeface(typeface);
        bioTextView.setTypeface(handwriting);
        textWearWeaponSuitTextView.setTypeface(handwriting);
        textWearSuitTextView.setTypeface(handwriting);
    }

    private void init(){
        user = this.getActivity().getSharedPreferences("user", MODE_PRIVATE);
        sp = this.getActivity().getSharedPreferences("userinfo",MODE_PRIVATE);
        autoLogin = user.getBoolean("isAutoLogin",false);
        userId = user.getString("userId", "userId");

        // 获取布局文件中的控件对象
        smartRefreshLayout=view.findViewById(R.id.lv_role_ref);
        ivBtn = view.findViewById(R.id.iv_avatar_btn);
        drawerLayout = view.findViewById(R.id.drawer_layout);
        ivAvatar = view.findViewById(R.id.iv_avatar);
        tvNickname = view.findViewById(R.id.tv_nickname);
        listView = view.findViewById(R.id.lv_list);
        todayStudyTime=view.findViewById(R.id.today_study_time_count);
        todaySteps=view.findViewById(R.id.today_run_steps_count);
        powerTextView=view.findViewById(R.id.power_count);
        intelligenceTextView=view.findViewById(R.id.intelligence_count);
        charmTextView=view.findViewById(R.id.charm_count);
        roleImageView=view.findViewById(R.id.role_image);
        roleWeaponImageView=view.findViewById(R.id.role_weapon_image);
        bioTextView=view.findViewById(R.id.tv_bio);
        comprehensiveTextView=view.findViewById(R.id.comprehensive_count);
        textWearSuitTextView=view.findViewById(R.id.text_wearSuit);
        textWearWeaponSuitTextView=view.findViewById(R.id.text_wearWeapon);
        // 绑定适配器
        setAdapter();

    }
    private void updatePage() {
        // 设置头像
        String avatarUrl = SPUtils.getString("imageUrl"+userId, null, getContext());
        if (avatarUrl != null) {
            Glide.with(this).load(avatarUrl).apply(requestOptions).into(ivAvatar);
            Glide.with(this).load(avatarUrl).apply(requestOptions).into(ivBtn);
        }
        // 设置昵称
        tvNickname.setText(user.getString("nickName", "Nickname"));
        //更新页面信息
        String s=sp.getString("userInfo", null);
        String img1 = null,img2=null;
        if(s!=null) {
            try {
                JSONObject jsonObject = new JSONObject(s);
                todayStudyTime.setText("今日学习时长:" + dff.format(new Double(jsonObject.getString("todayLearningTime")) )+ "小时");
                //更新步数
                todaySteps.setText("今日运动步数:"+ (int)StepUtil.getTodayStep(this.getContext()));
                if (StepUtil.getTodayStep(this.getContext())== 0) {
                    todaySteps.setText("今日运动步数:" + jsonObject.getString("todayStep"));
                }
                powerTextView.setText("智力:\n" + dfff.format(new Double(jsonObject.getString("intelligence"))));
                intelligenceTextView.setText("体力:\n" + dfff.format(new Double(jsonObject.getString("power"))));
                charmTextView.setText("魅力:\n" + dfff.format(new Double(jsonObject.getString("charm"))));
                comprehensiveTextView.setText("综合：\n" + dfff.format(new Double(jsonObject.getString("comprehensive"))));
                String bioString = jsonObject.getString("bio");
                if (bioString != null&&!bioString.equals("null")) {
                    bioTextView.setText(bioString);
                }
                tvNickname.setText(jsonObject.getString("nickName"));
                if (jsonObject.getString("wearWeapon") != null && !jsonObject.getString("wearWeapon").equals("null")) {
                    Glide.with(this).load(jsonObject.getString("wearWeapon")).into(roleWeaponImageView);
                    img1 = jsonObject.getString("wearWeapon");
                }
                if (jsonObject.getString("wearSuit") != null || !jsonObject.getString("wearWeapon").equals("null")) {
                    Glide.with(this).load(jsonObject.getString("wearSuit")).into(roleImageView);
                    img2 = jsonObject.getString("wearSuit");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        //无套装显示默认套装
        if(img2==null||img2.equals("null")){
            Glide.with(this).load("https://tlryjg.jiaohusheji.net/wp-content/uploads/2021/11/1636462787-Archaeologist27s_set.png").into(roleImageView);
        }
        //无武器显示默认武器
        if(img1==null||img1.equals("null")){
            Glide.with(this).load("https://tlryjg.jiaohusheji.net/wp-content/uploads/2019/12/mujian.png").into(roleWeaponImageView);
        }

        /*Glide.with(this)
                .load()
                .into(roleImageView);*/
        //String url="https://tse1-mm.cn.bing.net/th/id/OIP-C.DSOuQaO_SLmSoz_ccspN0gAAAA?w=174&h=180&c=7&r=0&o=5&dpr=1.3&pid=1.7";

    }
    //从后端读取信息并放入SP中
    private void initSp() {
        //从SP中获取userId
        String UID=null;
        sp = this.getActivity().getSharedPreferences("user", MODE_PRIVATE);
        UID = sp.getString("userId", "");
        OkHttpClient okHttpClient = new OkHttpClient();
        Constant.logger.info("开始从服务端获取UserInfo数据 userId=" + UID + "步数:" + StepUtil.getTodayStep(this.getContext()));
        Request request = new Request.Builder()
                //设置请求地址，请求方式默认get
                .url(Constant.BASE_URL + "userInfo/updateUserInfoStep?userId=" + UID + "&step=" + StepUtil.getTodayStep(this.getContext()))
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Constant.logger.warn("从服务端获取UserInfo数据: 失败", e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    String s = response.body().string();
                    JSONObject jsonObject = new JSONObject(s);
                    String msg = jsonObject.getString("msg");
                    Constant.logger.info("服务端Response: " + msg);
                    String jsonStr = jsonObject.getString("data");
                    if(!(jsonStr == null || "".equals(jsonStr))){
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putString("userInfo",jsonStr);
                        editor.commit();
                    }
                    //数据源发送改变，需要更新界面，使用Handler
                    Message message = new Message();
                    message.what = REFRESH;
                    myHandler.sendMessage(message);//发送到主线程的消息队列
                } catch (JSONException e) {
                    Constant.logger.warn("解析服务端Response: 失败", e);
                }
            }
        });
    }
    /**
     * 绑定适配器
     */
    private void setAdapter() {
        strings.add("设置");
        strings.add("关于我们");
        strings.add("退出登录");
        arrayAdapter = new MySettingAdapter(getContext(),strings,R.layout.ricardo_layout);
        listView.setAdapter(arrayAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0: // 设置
                        Intent intent1 = new Intent();
                        intent1.setClass(getContext(), SettingActivity.class);
                        startActivity(intent1);
                        break;
                    case 1: // 关于我们
                        Intent intent2 = new Intent();
                        intent2.setClass(getContext(), AboutUsActivity.class);
                        startActivity(intent2);
                        break;
                    case 2: // 退出登录
                    {
                        myDialog=new MyDialog(RoleFragment.this.getContext(),R.style.MyDialog);
                        myDialog.setTitle("温馨提示");
                        myDialog.setMessage("是否确认退出登录");
                        myDialog.setYesOnclickListener("确定", new MyDialog.onYesOnclickListener() {
                            @Override
                            public void onYesOnclick() {
                                // 获取Activity任务栈, 清除所有的Activity
                                ActivityManager manager = (ActivityManager) getContext().getSystemService(Context.ACTIVITY_SERVICE);
                                List<ActivityManager.AppTask> appTasks = manager.getAppTasks();
                                appTasks.get(0).finishAndRemoveTask();
                                editor = user.edit();
                                editor.putBoolean("isAutoLogin",false);
                                editor.commit();
                                // 跳转到最初的登录页面
                                Intent intent3 = new Intent();
                                intent3.setClass(getContext(), MainActivity.class);
                                startActivity(intent3);
                            }
                        });
                        myDialog.setNoOnclickListener("取消", new MyDialog.onNoOnclickListener() {
                            @Override
                            public void onNoClick() {
                                //Toast.makeText(getApplicationContext(),"早点休息",Toast.LENGTH_LONG).show();
                                myDialog.dismiss();
                            }
                        });
                        myDialog.show();
                        break;
                    }
                }
            }
        });
    }
}
